﻿/*
 * Copyright (c) HiSilicon (Shanghai) Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

#include "OperationLog.h"
#include "Global.h"

OperationLog::OperationLog()
    : burnFileName(""),
      startTime(""),
      endTime(""),
      comName(""),
      burnResult(0),
      file(nullptr)
{
    filePath = GetMsgFilePath();
}

OperationLog::~OperationLog()
{
}

void OperationLog::CloseFile()
{
    if (file != nullptr) {
        file->close();
        delete file;
        file = nullptr;
    }
}

void OperationLog::RecordIntoFile()
{
    QString cleanPath = QDir::cleanPath(filePath);
    if (cleanPath.isEmpty()) {
        return;
    }
    if (file == nullptr) {
        file = new QFile(cleanPath);
    }
    if (file == nullptr) {
        return;
    }
    file->open(QIODevice::Append);
    QTextStream in(file);
    in << "------------------------------------" << endl;
    in << QByteArray("烧写时间：") << startTime << "~" << endTime<< endl;
    in << QByteArray("烧写文件：") << burnFileName << endl;
    in << QByteArray("烧写bin文件：") << endl;
    for (int i = 0; i < binFileList.size(); i++) {
        in << i << "." << binFileList[i] << endl;
    }
    in << QByteArray("COM口：") << comName << endl;
    in << QByteArray("烧写结果：");
    if (burnResult == 0) {
        in << QByteArray("成功") << endl;
    } else {
        in << QByteArray("失败，") << burnResult << endl;
    }
    in << "------------------------------------" << endl;
    file->close();
}

void OperationLog::RecordFile(QByteArray str)
{
    QString cleanPath = QDir::cleanPath(filePath);
    if (cleanPath.isEmpty()) {
        return;
    }
    if (file == nullptr) {
        file = new QFile(cleanPath);
    }
    if (file == nullptr) {
        return;
    }
    file->open(QIODevice::Append);
    QTextStream in(file);
    in << "------------------------------------" << endl;
    in << str << endl;
    in << "------------------------------------" << endl;
}

QString OperationLog::GetMsgFilePath() const
{
    QString fileName = "";
    QString suffix = Global::dataTime + ".txt";

    QString replayPath = "optLog";
    int pathLen = replayPath.length();

    QString mFilePath = qApp->applicationDirPath() + "/optLog/";
    QDir logDir(mFilePath);
    logDir.mkdir(mFilePath);

    int hlfLen = QFileInfo(replayPath).suffix().length();
    fileName = mFilePath + replayPath.mid(0, pathLen - hlfLen) + suffix;

    return fileName;
}

void OperationLog::SetBurnFileName(QString strFileName)
{
    burnFileName = strFileName;
}

void OperationLog::SetBurnStartTime(QString strSartTime)
{
    startTime = strSartTime;
}

void OperationLog::SetBurnEndTime(QString strEndTime)
{
    endTime = strEndTime;
}

void OperationLog::SetBurnComNum(QString strComNum)
{
    comName = strComNum;
}

void OperationLog::SetBurnBinFile(QStringList strBinList)
{
    binFileList = strBinList;
}

void OperationLog::SetBurnResult(int result)
{
    burnResult = result;
}
